/*
 * @Author: chengsl
 * @Date: 2022-01-06 09:29:40
 * @LastEditors: chengsl
 * @LastEditTime: 2023-05-05 09:43:23
 * @Description: file content
 */
import { createRouter, createWebHistory } from 'vue-router'
import unifiedTip from '@/utils/unifiedTip'// 全局统一提示
const { Notification } = unifiedTip
import store from '../store'
import navList from './navList'

export var routes = [
	{
		name: '登录',
		path: '/login',
		component:() => import('../pages/login')
	},
	{
		name: '壁纸',
    path: '/subpage/wallpaper',
		components: {
      subpage: () => import('../pages/watermark/edit')
    },
		meta: {
			title: '壁纸制作'
		}
	}
]

function getRouterList(list) {
  list.forEach((item) => {
    if (item.children && item.children.length) {
      const tempItem = {
        path: item.path,
        name: item.name,
        component: item.component
      }
      routes.push(tempItem)
      getRouterList(item.children)
    } else {
      routes.push(item)
    }
  })
}
getRouterList(navList)

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  strict: false,
  // 切换页面，滚动到最顶部
  scrollBehavior: () => ({ left: 0, top: 0 })
})

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async(to, from, next) => {
	const whitePathArr = [
		'/login'
	]
  // console.log('router say:', to.path, '-', from.path, store)
  if (to.query.onlyShowMain === 'true' && store.state.onlyShowMain === false) {
		store.commit('setOnlyShowMain', true)
  } else if (
		store.state.onlyShowMain === true &&
    !Object.prototype.hasOwnProperty.call(to.query, 'onlyShowMain')
		) {
			store.commit('setOnlyShowMain', process.env.NODE_ENV === 'development' || false) // 40@remarks 本地开发默认只显示内容
		}
	if(whitePathArr.includes(to.path)) return next()
	const TOKEN = localStorage.token
	if(!TOKEN) {
		if(!whitePathArr.includes(to.path)) {
			Notification.error({
				title: '请先登录系统'
			})
		  return next('/login')
		}
	} else {
		const hasCustomerId = store.state.user.userInfo && store.state.user.userInfo.customerId
		if(!hasCustomerId) {
			try {
				await store.dispatch('user/setUserInfo') // 获取用户信息
			} catch (error) {
			  return next('/login')
			}
		}
	}
	next()
})

export default router
